package io.renren.modules.wcs;

import io.renren.common.utils.R;
import io.renren.datasource.annotation.DataSource;

import io.renren.modules.ioserver.IOServerService;
import io.renren.modules.wcs.enums.IOServerEnum;
import io.renren.modules.wcs.listenSlaveDB.SalveThread;
import io.renren.modules.wcs.listenSlaveDB.entity.TestEntity2;
import io.renren.modules.wcs.listenSlaveDB.service.TestService;
import io.renren.modules.wcs.listenSlaveDB.entity.ThreadFlag;
import io.renren.modules.websocket.MessageModule;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Author: 蔡翔
 * @Date: 2019/10/12 15:15
 * @Version 1.0
 */
@RestController
@Api(description = "wmc测试接口")
@RequestMapping("/wmcTest")
@DependsOn("springContextUtils")
public class WmcController {

    private static final Logger logger = LoggerFactory.getLogger(WmcController.class);


    @Autowired
    DDJService ddjService;

    @Autowired
    private TestService testService;

    @Autowired
    private MessageModule messageModule;


    private static SalveThread t = new SalveThread();

    /**
     * 往sql-server 里面插入数据
     **/
    @ApiOperation(value = "insert-slave源", notes = "insert-slave源")
    @PostMapping("/insertSlave")
    @DataSource("slave1")
    public R insertSlave(@RequestBody ThreadFlag threadFlag){
        int min = 1;
        int max = 1000;
        int intBounded = min + ((int) (new Random().nextFloat() * (max - min)));
        Integer a = threadFlag.getFlagAS();
        String aa = a.toString();

        TestEntity2 testEntity = new TestEntity2();
        testEntity.setUserNames(aa);
        testEntity.setPassword("123");
        testEntity.setId(intBounded);

        if(testService.save(testEntity)){
            return R.ok("插入成功");
        }else {
            return R.error("插入失败");
        }
    }

    /**
     *  监听sql-server 并且把数据 移植到mysql
     **/
    @ApiOperation(value = "监听slave数据源", notes = "监听slave数据源")
    @PostMapping("/listenSlaveDB")
    @DataSource("slave1")
    public R listenSlaveDB(@RequestBody ThreadFlag flag){
        //注意***
        //@DependsOn("springContextUtils")
        //Controller层必须加@DependsOn() 否则项目打包成jar包会报错空指针异常
        // 一个接口 就是一个nio 线程。不同时间段 调用相同接口，都是不同的线程在跑。
        Integer flages = flag.getFlagAS();
        System.err.println("当前nio线程："+Thread.currentThread().getName());

        if(flages == 1){
            if(!t.isAlive()){
                t.start();
            }
            return R.ok("线程已近 启动");
        }
        if(flages ==3){
            t.wakeup();
            return R.ok("线程已被唤醒");
        }else{
            //t.interrupt();
            t.shutdown();
            return R.error("线程已近关闭");
        }
    }

    //websocket 对 一个点
    @ApiOperation(value = "testWebsocketToOne", notes = "testWebsocketToOne")
    @GetMapping("/websockettest/{userId}/{msg}")
    public R testWebsocketToOne(@PathVariable("userId") String userId, @PathVariable("msg") String msg) {
        if(messageModule.sendMessageToSomeone(msg,userId)){
            return R.ok().put("status","success");
        }else {
            return R.error("发送失败");
        }
    }

    //websocket 对 所有人
    @ApiOperation(value = "testWebsocketToAll", notes = "testWebsocketToAll")
    @GetMapping("/websockettest/{msg}")
    public R testWebsocketToAll(@PathVariable("msg") String msg) throws IOException {
        if(messageModule.sendMessageToAll(msg)){
            return R.ok().put("status","success");
        }else {
            return R.error("发送失败");
        }
    }




    /**
     * caixiang
     * 给plc 堆垛机 修改(current )变量值
     **/
    @ApiOperation(value = "modifyDDJ2", notes = "modifyDDJ2")
    @PostMapping("/modifyDDJ2")
    public R modifyDDJ2(@RequestBody DDJArgEntity taksArgEntity) throws Exception {
        return R.ok().put("result",ddjService.modifyCurrentPLC(taksArgEntity));
    }



    /**
     * caixiang
     * 功能：给堆垛机 发任务 或者 监听堆垛机
     *  * 这个接口是启动监听 是否堆垛机任务完成 和 给改变堆垛机plc 值（变相给堆垛机发任务）。
     *  * type = 0     // 发任务
     *  * type = 1 // 监听plc
     *  *
     *  *结果：
     *  *type = 0
     *  *      3 => 代表ioserver 写入异常； 1 代表 成功（两个成功）；  -1 代表其他错误
     *  *type = 1
     *  *      1 代表成功  ; 2 代表设备报错 ; -1 代表 失败（其他错误） ；
     *
     **/
    @ApiOperation(value = "taskDDJ2", notes = "taskDDJ2")
    @PostMapping("/taskDDJ2")
    public R taskDDJ2(@RequestBody DDJArgEntity taksArgEntity) throws Exception {
        return R.ok().put("result",ddjService.sendTask(taksArgEntity));
    }

    @ApiOperation(value = "testLoggerErr", notes = "testLoggerErr")
    @PostMapping("/testLoggerErr")
    public R testLoggerErr() throws Exception {
        logger.error("测试错误");
        return R.ok();
    }



   /* @ApiOperation(value = "taskDDJ", notes = "taskDDJ")
    @PostMapping("/taskDDJ")
    public R taskDDJ(@RequestBody DDJArgEntity taksArgEntity) throws Exception {
        DDJRunnableCallable2<Integer> task = new DDJRunnableCallable2<>(taksArgEntity,ioServerService);

        logger.info("线程池是否关闭："+QGSThreadPool.executor.isShutdown());
        Future<?> future = QGSThreadPool.executor.submit(task);
        logger.info("是否正在执行："+future.isDone());
        Object r = new Object();
        try {
            r = future.get();
        } catch (InterruptedException e){
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        *//*threadPool.getExecutor().shutdown();
         *//*
        return R.ok().put("result",r);
    }*/
   /*//给plc 堆垛机 修改(current )变量值  (修改不能用Get 注解)
   @ApiOperation(value = "modifyDDJ", notes = "modifyDDJ")
   @PostMapping("/modifyDDJ")
   public R modifyDDJ(@RequestBody DDJArgEntity taksArgEntity) throws Exception {
       DDJArgEntity esew = taksArgEntity;
       Short destLayer = Short.valueOf(taksArgEntity.getDestLayer());
       Short destCol = Short.valueOf(taksArgEntity.getDestCol());
       Short takePosition = Short.valueOf(taksArgEntity.getTakePosition());

       Integer integer = ioServerService.setTagValue(IOServerEnum.Current_Layer.getCollectionPointName(), destLayer.toString(), 1);
       Integer integer2 = ioServerService.setTagValue(IOServerEnum.Current_Column.getCollectionPointName(), destCol.toString(), 1);
       Integer integer3 = ioServerService.setTagValue(IOServerEnum.Current_Position.getCollectionPointName(), takePosition.toString(), 1);
       if(integer ==0 &&integer2 ==0 &&integer3 ==0){
           return R.ok("写入plc 成功");
       }else {
           return R.error("写入plc失败");
       }
   }*/
}
